package com.example.other.oth;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import gui.ava.html.image.generator.HtmlImageGenerator;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;

public class QcDemo {
    private static void genQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
        HtmlImageGenerator imageGenerator = new HtmlImageGenerator();

//        Dimension dimension = new Dimension();
//        dimension.setSize(500, 500);
//        imageGenerator.setSize(dimension);

        String htmlstr = "<p>商品图片</p></br>\n" +
                "<p>price:156</p>\n" +
                "<img src=\"http://l1.51fanli.net/ocp/?s=320x320&q=100&u=/super/images/2018/12/5c18530d34351.jpg\">";

        imageGenerator.loadHtml(htmlstr);
        //--------------------------------------------------------------------------

        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, 20, 20);

        Path path = FileSystems.getDefault().getPath(filePath);
//        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

//        MatrixToImageWriter.toBufferedImage(bitMatrix);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics graphics = bufferedImage.getGraphics();
        graphics.drawImage(imageGenerator.getBufferedImage(), 0, 0,200, 400,null);
        graphics.drawImage(MatrixToImageWriter.toBufferedImage(bitMatrix), 0, 400, 60, 60, null);
        FileOutputStream out = new FileOutputStream("D:\\MyQRCode.png");

        // 释放此图形的上下文以及它使用的所有系统资源。
        graphics.dispose();
        //将绘制的图像生成至输出流
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        encoder.encode(bufferedImage);
        //关闭输出流
        out.close();

//        ImageIO.write(bufferedImage, "PNG", path.toFile());

    }

    public static void main(String[] args) throws IOException, WriterException {
        genQRCodeImage("https://super.fanli.com/h5/presale", 400, 800, "D:\\MyQRCode.png");
    }
}
